#include <chrono>
#include <iostream>
#include <semaphore>
#include <thread>
#include <chrono>
using namespace std;

void get_cmd();

bool flag_sem_timeout = false;
std::counting_semaphore cnt_sem(0);
void ThreadProc()
{
    while(true){
        std::cout << "[线程] 21 start" << std::endl; // 回应消息
        cnt_sem.acquire();
        std::cout << "[线程] 22 获得锁" << std::endl; // 回应消息
        cnt_sem.release();
        std::cout << "[线程] 23 释放锁" << std::endl; // 回应消息
        std::this_thread::sleep_for(std::chrono::seconds(3));
    }
}

int main()
{
    // 创建某个工作线程
    std::thread thrWorker(ThreadProc);
    std::cout << "[主] 11 开始\n"; // 消息
    thrWorker.detach();
    get_cmd();
    std::cout << "[主] 12 结束\n"; // 消息

    return 0;
}

void get_cmd()
{
    string cmd;
    bool ret;
    string help=" \
    1 获取信号量 \
    2 释放信号量 \
    t 切换超时获取/释放 \
    h 帮助 \
    q 退出 \
\n";
    cout << help << endl;

    while(true){
        cin >> cmd;
        if(cmd == "1"){
            // bin_sem.acquire(); 尽量不要使用acquire(), 开始运行时, 按1会形成死锁
            ret = cnt_sem.try_acquire();
            if(ret == false)
                cout << "获取信号量失败" << endl;
        }
        else if(cmd == "2"){
            cnt_sem.release();
        }
        // else if(cmd == "t")
        // {
        //     flag_sem_timeout = !flag_sem_timeout;
        // }
        else if(cmd == "h"){
            cout << help << endl;
        }
        else if(cmd == "q"){
            exit(0);
        }
        else{
            cerr << "not support cmd: " << cmd << endl;
            cout << help << endl;
        }
    }
}
